<?php
/**
 * Description:
 * Author: hezhizheng
 * Date: 2018/11/15
 * Time: 9:57
 * Created by Created by Panxsoft.
 */

namespace App\Services\Customers\Login;

use App\Exceptions\ApiErrCode;
use App\Exceptions\ApiException;
use App\Http\Requests\Customers\CustomerLoginRequest;
use App\Models\Customers\Customer;
use App\Services\Customers\Register\EmailRegisterService;
use App\Services\Utils\ApiChecker;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\JWT;
use Tymon\JWTAuth\JWTGuard;

class NormaLoginService
{
    use ApiChecker;

    private $customer;

    public function __construct()
    {
        $this->customer = new Customer;
    }


    /**
     * @param CustomerLoginRequest $request
     *
     * @return Customer|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|null|object
     * @throws \Exception
     */
    public function login(CustomerLoginRequest $request)
    {
        $admin = $this->customer
            ->where('email', $request->account)
            ->orWhere(function(Builder $query) use($request){
                $query->where('telephone', $request->account)
                    ->where('dial_code', $request->dial_code);
            })
            ->first();

        $this->checkIsTrue($admin, trans('customer.account_does_not_exist'));
        $this->checkIsTrue($admin->status === Customer::STATUS_ENABLE, trans('customer.disabled'));

        /** @var JWTGuard|JWT $jwt */
        $jwt = Auth::guard(Customer::GUARD_NAME);

        try {
            if ($admin->email) {
                $jwt_token = $jwt->attempt([
                    'email'    => $admin->email,
                    'password' => $request->password
                ]);
            } elseif ($admin->telephone) {
                $jwt_token = $jwt->attempt([
                    'dial_code' => $admin->dial_code,
                    'telephone' => $admin->telephone,
                    'password'  => $request->password,
                ]);
            } else {
                $jwt_token = null;
            }

            $this->passwordVerifyCheck($jwt_token);
            // save token
            $admin->update(['jwt_token' => $jwt_token]);

        } catch (JWTException $e) {
            if (config('app.debug')) throw $e;

            throw New ApiException(ApiErrCode::TOKEN_GENERATE_FAIL, trans('customer.unable_to_generate_token'));
        }

        // 关联第三方登录账号
        (new EmailRegisterService)->relateSocialiteAccount($admin->customer_id);

        $admin->addHidden(['password', 'salt']);

        return $admin;
    }

    private function passwordVerifyCheck($token)
    {
        if (!$token) {
            throw New ApiException(ApiErrCode::INVALID_PASSWORD, trans('customer.wrong_password'));
        }
    }
}